#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>

using namespace std;

class QueryResult;

class TextQuery;

void runQueries(ifstream &infile);

int main()
{
    ifstream if;
    TextQuery(if);
    // TODO
    return 0;
}

class TextQuery
{
public:
    using line_no = vector<string>::size_type;
    TextQuery(ifstream &);
    QueryResult query(const string &) const;

private:
    shared_ptr<vector<string> > file;
    map<string, shared_ptr<set<line_no> > > wm;
};

class QueryResult
{
    friend ostream &print(ostream &, const QueryResult &);

public:
    QueryResult(string s, shared_ptr<set<line_no> > p, shared_ptr<vector<string> > f) : sought(s), lines(p), file(f) {}

private:
    string sought;
    shared_ptr<set<line_no> > lines;
    shared_ptr<vector<string> > file;
}

TextQuery::TextQuery(ifstream &is) : file(new vector<string>)
{
    string text;
    while (getline(is, text)) // 对文件中每一行
    {
        file->push_back(text);    // 保存此行文本
        int n = file->size() - 1; // 当前行号
        istringstream line(text); // 将行文本分解为单词
        string word;
        while (line >> word) // 对行中每个单词
        {
            // 如果单词不在wm中，以之为下标在wm中添加一项
            auto &lines = wm[word];            // lines是一个shared_ptr
            if (!lines)                        // 在我们第一次遇到这个单词时，此指针为空
                lines.reset(new set<line_no>); // 分配一个新的set
            lines->insert(n);                  // 将此行号插入set中
        }
    }
}

QueryResult TextQuery::query(const string &sought) const // const在函数参数外，可以修饰成员函数，在此函数中不能修改本类数据成员的值
{
    static shared_ptr<set<line_no> > nodata(new set<line_no>);
    auto loc = wm.find(sought);
    if (loc == wm.end())
        return QueryResult(sought, nodata, file);
    else
        return QueryResult(sought, loc->second, file);
}

ostream &print(ostream &os, const QueryResult &qr)
{
    os << qr.sought << "occurs" << qr.lines->size() << " " << make_plural(qr.lines->size(), "time", "s") << endl;
    for(auto num : *qr.lines)
        os << "\t(line " << num + 1 << ")" << *(qr.file->begin() + num) << endl;
    return os;
}

void runQueries(ifstream &infile)
{
    TextQuery tq(infile);
    while (true)
    {
        cout << "enter word to look for, or q to quit: ";
        string s;
        if (!(cin >> s) || s == "q")
            break;
        print(cout, tq.query(s)) << endl;
    }
}